package cc.rengu.redp.bizimpl.upmp.service.impl;

import cc.rengu.redp.bizimpl.enums.BizDataAuditStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizDataStatusEnum;
import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpSysParamService;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.utils.DateUtil;
import cc.rengu.redp.common.utils.SortUtil;
import cc.rengu.redp.bizimpl.upmp.dao.IcEmvInfoMapper;
import cc.rengu.redp.bizimpl.upmp.domain.IcEmvInfo;
import cc.rengu.redp.bizimpl.upmp.domain.IcEmvInfoBean;
import cc.rengu.redp.bizimpl.upmp.service.IcEmvInfoService;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author LiuYuLiang.LL
 */
@Service
@DS("upmp")
public class IcEmvInfoServiceImpl extends ServiceImpl<IcEmvInfoMapper, IcEmvInfo> implements IcEmvInfoService {
    @Autowired
    private IUpmpSysParamService upmpSysParamService;

    @Override
    public IPage<IcEmvInfo> findByPage(QueryRequest request, IcEmvInfo info) {
        try {
            LambdaQueryWrapper<IcEmvInfo> queryWrapper = new LambdaQueryWrapper<>();
            if (StringUtils.isNotBlank(info.getInstId())) {
                queryWrapper.eq(IcEmvInfo::getInstId, info.getInstId());
            } else {
                UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
                queryWrapper.eq(IcEmvInfo::getInstId, user.getInstId());
            }
            if (StringUtils.isNotBlank(info.getParaId())) {
                queryWrapper.likeRight(IcEmvInfo::getParaId, info.getParaId());
            }
            queryWrapper.likeRight(IcEmvInfo::getUsageKey, "0");
            queryWrapper.orderByDesc(IcEmvInfo::getCreateTime);
            Page<IcEmvInfo> page = new Page<>();
            SortUtil.handlePageSort(request, page, true);
            return this.page(page, queryWrapper);
        } catch (Exception e) {
            log.error("查询失败", e);
            return null;
        }
    }
    
    @Override
    @Transactional
    public void create(IcEmvInfo entity) {
        // 获取当前登录用户信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        String lastUpddt = DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN);

        entity.setInstId(user.getInstId());
        entity.setStatus(BusinessContainer.data_sta_01);
        entity.setAuditStatus(BusinessContainer.status_02);
        entity.setOprId(user.getId());
        entity.setCrtOrgId(user.getOrgCode());
        entity.setCreateTime(lastUpddt);
        entity.setLastOprId(user.getId());
        entity.setLastUpdateTime(lastUpddt);

        String aid = "9F0608" + entity.getAid();
        String yybb = "9F0802" + entity.getYybb();
        String yyzsf = "DF0101" + entity.getYyzsf();
        String tacqs = "DF1105" + entity.getTacqs();
        String taclj = "DF1205" + entity.getTaclj();
        String tacjj = "DF1305" + entity.getTacjj();
        String aa = entity.getZdzdxe();

        int cc = Integer.parseInt(aa);
        String zzxe = Integer.toHexString(cc);
        String zdzdxe = "9F1B04";
        for (int i = zzxe.length(); i < 8; i++) {
            zdzdxe += "0";
        }
        zdzdxe += zzxe;
        String fz = "DF1504";
        for (int i = entity.getFz().length(); i < 8; i++) {
            fz += "0";
        }
        fz += entity.getFz();
        String zdbfs = "DF1601" + entity.getZdbfs();
        String xzdbfs = "DF1701" + entity.getXzdbfs();
        String qsddol = "DF1403" + entity.getQsddol();
        String pinnl = "DF1801" + entity.getPinnl();
        String val = aid + yyzsf + yybb + tacqs + taclj + tacjj + zdzdxe + fz + zdbfs + xzdbfs + qsddol + pinnl;

        if (entity.getDzxjxe() != null && entity.getDzxjxe().length() > 0) {
            String index = String.format("%012d", Integer.parseInt(entity.getDzxjxe(), 16));
            String dzxjxe = "DF1906" + index;
            val += dzxjxe;
        }
        if (entity.getFdxqtjxe() != null && entity.getFdxqtjxe().length() > 0) {
            String index = String.format("%012d", Integer.parseInt(entity.getFdxqtjxe(), 16));
            String fdxqtjxe = "DF1906" + index;
            val += fdxqtjxe;
        }
        if (entity.getFdxqxe() != null && entity.getFdxqxe().length() > 0) {
            String index = String.format("%012d", Integer.parseInt(entity.getFdxqxe(), 16));
            String fdxqxe = "DF2006" + index;
            val += fdxqxe;
        }
        if (entity.getYzffsxxe() != null && entity.getYzffsxxe().length() > 0) {
            String index = String.format("%012d", Integer.parseInt(entity.getYzffsxxe(), 16));
            String yzffsxxe = "DF2016" + index;
            val += yzffsxxe;
        }

        entity.setParaId(entity.getAid());
        entity.setParaVal(val);
        entity.setUsageKey("0");
        entity.setParaIdx(entity.getYybb());
        entity.setParaOrg("CA");
        entity.setParaSta("I");
        entity.setParaLen(((Integer) entity.getParaVal().length()).toString());
        this.baseMapper.insert(entity);
    }

    @Override
    @Transactional
    public void update(IcEmvInfo entity) {
        // 获取当前登录用户信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        String lastUpddt = DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN);
        // 修改
        entity.setAuditStatus(BusinessContainer.status_42);
        entity.setLastOprId(user.getId());
        entity.setLastUpdateTime(lastUpddt);

        String aid = "9F0608" + entity.getAid();
        String yybb = "9F0802" + entity.getYybb();
        String yyzsf = "DF0101" + entity.getYyzsf();
        String tacqs = "DF1105" + entity.getTacqs();
        String taclj = "DF1205" + entity.getTaclj();
        String tacjj = "DF1305" + entity.getTacjj();
        String aa = entity.getZdzdxe();

        int cc = Integer.parseInt(aa);
        String zzxe = Integer.toHexString(cc);
        String zdzdxe = "9F1B04";
        for (int i = zzxe.length(); i < 8; i++) {
            zdzdxe += "0";
        }
        zdzdxe += zzxe;
        String fz = "DF1504";
        for (int i = entity.getFz().length(); i < 8; i++) {
            fz += "0";
        }
        fz += entity.getFz();
        String zdbfs = "DF1601" + entity.getZdbfs();
        String xzdbfs = "DF1701" + entity.getXzdbfs();
        String qsddol = "DF1403" + entity.getQsddol();
        String pinnl = "DF1801" + entity.getPinnl();
        String val = aid + yyzsf + yybb + tacqs + taclj + tacjj + zdzdxe + fz + zdbfs + xzdbfs + qsddol + pinnl;

        if (entity.getDzxjxe() != null && entity.getDzxjxe().length() > 0) {
            String index = String.format("%012d", Integer.parseInt(entity.getDzxjxe(), 16));
            String dzxjxe = "DF1906" + index;
            val += dzxjxe;
        }
        if (entity.getFdxqtjxe() != null && entity.getFdxqtjxe().length() > 0) {
            String index = String.format("%012d", Integer.parseInt(entity.getFdxqtjxe(), 16));
            String fdxqtjxe = "DF1906" + index;
            val += fdxqtjxe;
        }
        if (entity.getFdxqxe() != null && entity.getFdxqxe().length() > 0) {
            String index = String.format("%012d", Integer.parseInt(entity.getFdxqxe(), 16));
            String fdxqxe = "DF2006" + index;
            val += fdxqxe;
        }
        if (entity.getYzffsxxe() != null && entity.getYzffsxxe().length() > 0) {
            String index = String.format("%012d", Integer.parseInt(entity.getYzffsxxe(), 16));
            String yzffsxxe = "DF2016" + index;
            val += yzffsxxe;
        }

        entity.setParaId(entity.getAid());
        entity.setParaVal(val);
        entity.setUsageKey("0");
        entity.setParaIdx(entity.getYybb());
        entity.setParaOrg("CA");
        entity.setParaSta("I");
        entity.setParaLen(((Integer) entity.getParaVal().length()).toString());
        this.baseMapper.updateById(entity);
    }

    @Override
    @Transactional
    public void newCreate(IcEmvInfo entity) {
        // 获取当前登录用户信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        String lastUpddt = DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN);

        entity.setInstId(user.getInstId());
        entity.setStatus(BusinessContainer.data_sta_01);
        entity.setAuditStatus(BusinessContainer.status_02);
        entity.setOprId(user.getId());
        entity.setCrtOrgId(user.getOrgCode());
        entity.setCreateTime(lastUpddt);
        entity.setLastOprId(user.getOrgCode());
        entity.setLastUpdateTime(lastUpddt);


        IcEmvInfoBean icemvinfobean = new IcEmvInfoBean();


        icemvinfobean.setASI(entity.getYyzsf());//应用指示符
        icemvinfobean.setAPP_VER(entity.getYybb());//应用版本号
        icemvinfobean.setTAC_DEF(entity.getTacqs());//TAC-缺省
        icemvinfobean.setTAC_OL(entity.getTaclj());//TAC-联机
        icemvinfobean.setTAC_REJECT(entity.getTacjj());//TAC-拒绝
        icemvinfobean.setLWM(entity.getZdzdxe());//终端最低限额
        icemvinfobean.setLAND_VAL(entity.getFz());//偏置随机选择的阈值
        icemvinfobean.setMAX_PCT(entity.getZdbfs());//偏置随机选择的最大目标百分数
        icemvinfobean.setTARGET_PCT(entity.getXzdbfs());//随机选择的目标百分数
        icemvinfobean.setDDOL_DEF(entity.getQsddol());//缺省DDL
        icemvinfobean.setPIN_ABILITY(entity.getPinnl());//终端联机PIN支持能力
        icemvinfobean.setOFFLINE_HLM(entity.getDzxjxe());//终端电子现金交易限额
        icemvinfobean.setUNCONTACT_LLM(entity.getFdxqtjxe());//非接触读写器脱机最低限额
        icemvinfobean.setUNCONTACT_HLM(entity.getFdxqxe());//非接触读写器脱机交易限额
        icemvinfobean.setCVM(entity.getYzffsxxe());//读写器持卡人验证方法(CVM)所需限制


        entity.setUsageKey("0");
        entity.setParaVal(JSON.toJSONString(icemvinfobean));
        entity.setParaIdx(entity.getYybb());
        entity.setParaSta("I");
        entity.setParaLen(((Integer) entity.getParaVal().length()).toString());
        this.baseMapper.insert(entity);
    }

    @Override
    @Transactional
    public void newUpdate(IcEmvInfo entity) {
        // 获取当前登录用户信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        String lastUpddt = DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN);
        // 修改
        entity.setAuditStatus(BusinessContainer.status_42);
        entity.setLastOprId(user.getId());
        entity.setLastUpdateTime(lastUpddt);

        IcEmvInfoBean icemvinfobean = new IcEmvInfoBean();
        icemvinfobean.setASI(entity.getYyzsf());//应用指示符
        icemvinfobean.setAPP_VER(entity.getYybb());//应用版本号
        icemvinfobean.setTAC_DEF(entity.getTacqs());//TAC-缺省
        icemvinfobean.setTAC_OL(entity.getTaclj());//TAC-联机
        icemvinfobean.setTAC_REJECT(entity.getTacjj());//TAC-拒绝
        icemvinfobean.setLWM(entity.getZdzdxe());//终端最低限额
        icemvinfobean.setLAND_VAL(entity.getFz());//偏置随机选择的阈值
        icemvinfobean.setMAX_PCT(entity.getZdbfs());//偏置随机选择的最大目标百分数
        icemvinfobean.setTARGET_PCT(entity.getXzdbfs());//随机选择的目标百分数
        icemvinfobean.setDDOL_DEF(entity.getQsddol());//缺省DDL
        icemvinfobean.setPIN_ABILITY(entity.getPinnl());//终端联机PIN支持能力
        icemvinfobean.setOFFLINE_HLM(entity.getDzxjxe());//终端电子现金交易限额
        icemvinfobean.setUNCONTACT_LLM(entity.getFdxqtjxe());//非接触读写器脱机最低限额
        icemvinfobean.setUNCONTACT_HLM(entity.getFdxqxe());//非接触读写器脱机交易限额
        icemvinfobean.setCVM(entity.getYzffsxxe());//读写器持卡人验证方法(CVM)所需限制


        entity.setUsageKey("0");
        entity.setParaVal(JSON.toJSONString(icemvinfobean));
        entity.setParaIdx(entity.getYybb());
        entity.setParaSta("I");
        entity.setParaLen(((Integer) entity.getParaVal().length()).toString());
        this.baseMapper.updateById(entity);
    }

    @Override
    @Transactional
    public void delete(String[] ids) {
        List<String> list = Arrays.asList(ids);
        this.baseMapper.deleteBatchIds(list);
    }

    @Override
    public void updIcemv(IcEmvInfo icEmvInfo) {
        saveData(icEmvInfo);
    }

    @Override
    public void addIcemv(IcEmvInfo icEmvInfo) {
        saveData(icEmvInfo);
    }

    private void saveData(IcEmvInfo icEmvInfo) {
        String optFlag = icEmvInfo.getOptFlag();
        String lastUpddt = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        java.util.Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        icEmvInfo.setUsageKey("0");
        icEmvInfo.setParaOrg("CA");
        icEmvInfo.setParaLen(((Integer) icEmvInfo.getParaVal().length()).toString());
        if ("add".equals(optFlag)) {
            icEmvInfo.setParaSta(PageOptFlagEnum.OPT_FLAG_ADD.getBizOpr());
            icEmvInfo.setStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
            icEmvInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
            icEmvInfo.setCrtOrgId(user.getId());
            icEmvInfo.setOprId(user.getId());
            icEmvInfo.setCreateTime(lastUpddt);

            this.save(icEmvInfo);
        }else if ("upd".equals(optFlag)) {
            icEmvInfo.setParaSta(PageOptFlagEnum.OPT_FLAG_UPDATE.getBizOpr());
            icEmvInfo.setLastOprId(user.getId());
            icEmvInfo.setLastUpdateTime(lastUpddt);
            icEmvInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());

            baseMapper.updateById(icEmvInfo);
        }


    }
}
